package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.dto.pyq.PyqComment;
import com.uzai.common.dto.pyq.PyqCommentDto;
import com.uzai.common.dto.pyq.PyqFollowSendDto;
import com.uzai.common.dto.pyq.PyqInfoDto;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.LogBizTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.pyq.pyqfollowconfig.PyqFollowConfigQuery;
import com.uzai.console.entity.PyqFollowConfig;
import com.uzai.console.entity.PyqFollowedComment;
import com.uzai.console.entity.PyqFollowedContent;
import com.uzai.console.mapper.PyqFollowConfigMapper;
import com.uzai.console.mapper.PyqFollowContentMapper;
import com.uzai.console.mapper.PyqFollowedCommentMapper;
import com.uzai.console.mapper.PyqFollowedContentMapper;
import com.uzai.console.service.pyq.PyqFollowSendService;
import com.uzai.console.service.pyq.PyqFollowSendSyncService;
import com.uzai.console.service.ratelimit.RatelimitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 朋友圈跟发配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqFollowSendSyncServiceImpl implements PyqFollowSendSyncService {

    Logger logger = LoggerFactory.getLogger(PyqFollowSendSyncServiceImpl.class);

    @Autowired
    private PyqFollowConfigMapper pyqFollowConfigMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private PyqFollowSendService pyqFollowSendService;
    @Autowired
    private PyqFollowedContentMapper pyqFollowedContentMapper;
    @Autowired
    private PyqFollowedCommentMapper pyqFollowedCommentMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 跟发朋友圈发送
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    //@Async("taskExecutor")
    public void followSendSync(PyqFollowSendDto pyqFollowSendDto){

        logger.info("-----调用朋友圈跟发功能--发送朋友圈任务--xxlJob start--pyqFollowSendDto={}", JSONObject.toJSONString(pyqFollowSendDto));

        //限流判断-同一个朋友圈同一个机器人1分钟只能调用一次
        String key = pyqFollowSendDto.getSnsId() + "_" + pyqFollowSendDto.getDeviceUniqueId();
        boolean inRateLimit = ratelimitService.inRateLimit("followSendPyq-key=" + key,1,60);
        if (!inRateLimit){
            //logger.info("--inRateLimit false. tradeno={}",alipayDetail.getTradeno());
            return;
        }

        //查询当前所有开启的自动发圈的配置方案
        int now = DateUtil.getNowTime();
        String yyyyMMdd = Tools.getDateFormat(new Date(), "yyyy-MM-dd");

        PyqFollowConfigQuery pyqFollowConfigQuery = new PyqFollowConfigQuery();
        pyqFollowConfigQuery.setMerId(pyqFollowSendDto.getMerId());
        pyqFollowConfigQuery.setStatus(1); //启动
        pyqFollowConfigQuery.setDeviceUniqueId(pyqFollowSendDto.getDeviceUniqueId());

        //查询所有的跟发配置记录
        Page<PyqFollowConfig> page = new Page<>();
        page.setCurrent(1);//只查第一页
        page.setSize(10); //每页查询10个
        page.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart = 0L;
        List<PyqFollowConfig> pyqFollowConfigList = pyqFollowConfigMapper.findByList(page, pyqFollowConfigQuery);
        while (pyqFollowConfigList != null && pyqFollowConfigList.size() > 0){
            for (PyqFollowConfig pyqFollowConfig : pyqFollowConfigList){
                try{
                    if(pyqFollowConfig.getId().longValue() > idStart.longValue()){
                        idStart = pyqFollowConfig.getId();
                    }
                    //自动发送朋友圈
                    pyqFollowSendService.followSendPyq(pyqFollowSendDto, pyqFollowConfig);
                }catch (Exception e){

                }
            }
            pyqFollowConfigQuery.setIdStart(idStart);
            pyqFollowConfigList = pyqFollowConfigMapper.findByList(page, pyqFollowConfigQuery);
        }

        //删除限流
        redisTemplate.delete(key);
    }

    /**
     * 跟发朋友圈发送内容
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    @Async("taskExecutor")
    public void followSendContentSync(PyqInfoDto pyqInfoDto){

        logger.info("-----朋友圈跟发--调用朋友圈内容发送任务--xxlJob start--pyqInfoDto={}", JSONObject.toJSONString(pyqInfoDto));

        //限流判断-同一个朋友圈由同一个监控机器人1分钟只能调用一次
        String key = pyqInfoDto.getSnsId() + "_" + pyqInfoDto.getDeviceUniqueId();
        boolean inRateLimit = ratelimitService.inRateLimit("followSendPyqContent-key=" + key,1,30);
        if (!inRateLimit){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                    pyqInfoDto.getMerId(), 0, pyqInfoDto.getDeviceUniqueId(),
                    "",0L,
                    "同一个朋友圈由同一个监控机器人1分钟只能调用一次")));

            //logger.info("--inRateLimit false. tradeno={}",alipayDetail.getTradeno());
            return;
        }

        //查询此朋友圈id是否已经发送过
        PyqFollowedContent pyqFollowedContent = pyqFollowedContentMapper.selectByDeviceUniqueIdAndSnsId(pyqInfoDto.getDeviceUniqueId(), pyqInfoDto.getSnsId());
        if(pyqFollowedContent != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此朋友圈id已经发送过");
        }else{//等于null,插入数据库
            pyqFollowedContent = new PyqFollowedContent();
            pyqFollowedContent.setId(IdWorker.getId());
            pyqFollowedContent.setMerId(pyqInfoDto.getMerId());
            pyqFollowedContent.setDeviceUniqueId(pyqInfoDto.getDeviceUniqueId());
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getById(pyqInfoDto.getDeviceType());
            if(deviceTypeEnum != null){
                pyqFollowedContent.setDeviceType(deviceTypeEnum.getKey());
            }
            pyqFollowedContent.setSnsId(pyqInfoDto.getSnsId());
            pyqFollowedContent.setReleaseWxid(pyqInfoDto.getReleaseWxid());
            pyqFollowedContent.setReleaseNickname(pyqInfoDto.getReleaseNickname());
            pyqFollowedContent.setReleaseTime(pyqInfoDto.getReleaseTime());
            pyqFollowedContent.setSendTime(pyqInfoDto.getSendTime());
            pyqFollowedContent.setContent(pyqInfoDto.getContent());
            pyqFollowedContent.setImg(Tools.getStrEmpty(JSONObject.toJSONString(pyqInfoDto.getImgList())));
            pyqFollowedContent.setAttachType(pyqInfoDto.getAttachType());
            pyqFollowedContent.setFeedMedia(Tools.getStrEmpty(JSONObject.toJSONString(pyqInfoDto.getMediaList())));
            pyqFollowedContent.setVideoNumber(Tools.getStrNull(JSONObject.toJSONString(pyqInfoDto.getPyqVideoNumberDto())));
            int now = DateUtil.getNowTime();
            pyqFollowedContent.setCreateTime(now);
            pyqFollowedContent.setUpdateTime(now);
            pyqFollowedContentMapper.insertSelective(pyqFollowedContent);
        }

        //查询当前所有开启的自动发圈的配置方案
        int now = DateUtil.getNowTime();
        String yyyyMMdd = Tools.getDateFormat(new Date(), "yyyy-MM-dd");
        PyqFollowConfigQuery pyqFollowConfigQuery = new PyqFollowConfigQuery();
        pyqFollowConfigQuery.setMerId(pyqInfoDto.getMerId());
        pyqFollowConfigQuery.setStatus(1); //启动
        pyqFollowConfigQuery.setDeviceUniqueId(pyqInfoDto.getDeviceUniqueId());//查询监控机器人的任务
        pyqFollowConfigQuery.setWxid(pyqInfoDto.getReleaseWxid());             //被监控机器人wxid的任务
        //查询所有的跟发配置记录
        Page<PyqFollowConfig> page = new Page<>();
        page.setCurrent(1);//只查第一页
        page.setSize(10); //每页查询10个
        page.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart = 0L;
        List<PyqFollowConfig> pyqFollowConfigList = pyqFollowConfigMapper.findByList(page, pyqFollowConfigQuery);
        while (pyqFollowConfigList != null && pyqFollowConfigList.size() > 0){
            for (PyqFollowConfig pyqFollowConfig : pyqFollowConfigList){
                try{
                    if(pyqFollowConfig.getId().longValue() > idStart.longValue()){
                        idStart = pyqFollowConfig.getId();
                    }
                    //自动发送朋友圈
                    pyqFollowSendService.followSendPyqContent(pyqInfoDto, pyqFollowConfig);
                }catch (Exception e){
                }
            }
            pyqFollowConfigQuery.setIdStart(idStart);
            pyqFollowConfigList = pyqFollowConfigMapper.findByList(page, pyqFollowConfigQuery);
        }

        //删除限流
        redisTemplate.delete(key);
    }

    /**
     * 跟发朋友圈发送评论
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    @Async("taskExecutor")
    public void followSendCommentSync(PyqCommentDto pyqCommentDto){

        logger.info("-----朋友圈跟发--调用朋友圈评论发送任务--xxlJob start--pyqCommentDto={}", JSONObject.toJSONString(pyqCommentDto));

        //评论列表
        List<PyqComment> commentList = pyqCommentDto.getList();
        if(commentList == null || commentList.size() ==0){
            return;
        }
        //朋友圈id
        String snsId = commentList.get(0).getSnsId();
        //限流判断-同一个朋友圈同一个监控机器人1分钟只能调用一次
        String key = snsId + "_" + pyqCommentDto.getDeviceUniqueId();
        boolean inRateLimit = ratelimitService.inRateLimit("followSendPyqComment-key=" + key,1,30);
        if (!inRateLimit){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                    pyqCommentDto.getMerId(), 0, pyqCommentDto.getDeviceUniqueId(),
                    "",0L,
                    "同一个朋友圈评论由同一个监控机器人1分钟只能调用一次")));
            return;
        }

        //循环评论列表
        //新建一个评论列表封装还未发送的评论
        List<PyqComment> pyqCommentList_new = new ArrayList<>();
        for(PyqComment pyqComment : commentList){
            //查询此朋友圈id评论是否已经发送过
            PyqFollowedComment pyqFollowedComment = pyqFollowedCommentMapper.selectByDeviceUniqueIdAndSnsIdAndCommentId(pyqCommentDto.getDeviceUniqueId(), pyqComment.getSnsId(), pyqComment.getCommentId());
            if(pyqFollowedComment != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此朋友圈的评论id已经发送过");
            }else{//等于null,插入数据库
                pyqFollowedComment = new PyqFollowedComment();
                pyqFollowedComment.setId(IdWorker.getId());
                pyqFollowedComment.setMerId(pyqCommentDto.getMerId());
                pyqFollowedComment.setDeviceUniqueId(pyqCommentDto.getDeviceUniqueId());
                DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getById(pyqCommentDto.getDeviceType());
                if(deviceTypeEnum != null){
                    pyqFollowedComment.setDeviceType(deviceTypeEnum.getKey());
                }
                pyqFollowedComment.setSnsId(pyqComment.getSnsId());
                pyqFollowedComment.setCommentId(pyqComment.getCommentId());
                pyqFollowedComment.setCommentWxid(pyqComment.getCommentWxid());
                pyqFollowedComment.setCommentNick(pyqComment.getCommentNick());
                pyqFollowedComment.setContent(pyqComment.getContent());
                pyqFollowedComment.setCommentTime(pyqComment.getCommentTime());
                int now = DateUtil.getNowTime();
                pyqFollowedComment.setCreateTime(now);
                pyqFollowedComment.setUpdateTime(now);
                pyqFollowedCommentMapper.insertSelective(pyqFollowedComment);
                //封装本次需要发送的评论
                pyqCommentList_new.add(pyqComment);
            }
        }

        //有需要发送的评论
        if(pyqCommentList_new != null && pyqCommentList_new.size() > 0){
            //重置参数，将本次需要发送的评论替换
            pyqCommentDto.setList(pyqCommentList_new);
            //查询当前所有开启的自动发圈的配置方案
            int now = DateUtil.getNowTime();
            String yyyyMMdd = Tools.getDateFormat(new Date(), "yyyy-MM-dd");
            PyqFollowConfigQuery pyqFollowConfigQuery = new PyqFollowConfigQuery();
            pyqFollowConfigQuery.setMerId(pyqCommentDto.getMerId());
            pyqFollowConfigQuery.setStatus(1); //启动
            pyqFollowConfigQuery.setDeviceUniqueId(pyqCommentDto.getDeviceUniqueId());
            pyqFollowConfigQuery.setWxid(pyqCommentList_new.get(0).getCommentWxid());      //获取第一个评论的wxid作为被监控机器人wxid
            //查询所有的跟发配置记录
            Page<PyqFollowConfig> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<PyqFollowConfig> pyqFollowConfigList = pyqFollowConfigMapper.findByList(page, pyqFollowConfigQuery);
            while (pyqFollowConfigList != null && pyqFollowConfigList.size() > 0){
                for (PyqFollowConfig pyqFollowConfig : pyqFollowConfigList){
                    try{
                        if(pyqFollowConfig.getId().longValue() > idStart.longValue()){
                            idStart = pyqFollowConfig.getId();
                        }
                        //自动发送朋友圈
                        pyqFollowSendService.followSendPyqComment(pyqCommentDto, pyqFollowConfig);
                    }catch (Exception e){
                    }
                }
                pyqFollowConfigQuery.setIdStart(idStart);
                pyqFollowConfigList = pyqFollowConfigMapper.findByList(page, pyqFollowConfigQuery);

            }
        }
        //删除限流
        redisTemplate.delete(key);
    }

    /**
     * 异步删除6小时之前的跟发记录
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    @Async("taskExecutor")
    @Override
    public void deletePyqFollowSendSync() {
        int deleteDay = DateUtil.getNowTime() - 6*3600;
        pyqFollowSendService.deleteBeforeDay(deleteDay);
    }

}
